﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Windows.Media;
using MediaAssistant.DAL;
using MefBasic.Helper;

namespace MediaAssistant.Management
{
    [Export]
    public class MusicDurationUpdater : BackgroundScanner
    {
        private Queue<Music> MusicQueue { get; set; }
        private MediaPlayer MediaPlayer { get; set; }

        public MusicDurationUpdater()
        {
            Name = "Music Duration Updater";
            MusicQueue = new Queue<Music>();
            MediaPlayer = new MediaPlayer { IsMuted = true };
            MediaPlayer.MediaOpened += HandleMediaOpened;
            MediaPlayer.MediaFailed += HandleMediaFailed;
            IsOpening = false;
        }
        private void HandleMediaFailed(object sender, ExceptionEventArgs e)
        {
            MediaPlayer.Stop();
            MediaPlayer.Close();
            IsOpening = false;
        }

        public bool IsOpening { get; set; }

        private void HandleMediaOpened(object sender, EventArgs e)
        {
            DatabaseManager.Instance.UpdateDuration(CurrentMusic, MediaPlayer.NaturalDuration);
            MediaPlayer.Stop();
            MediaPlayer.Close();
            IsOpening = false;
        }
        private Music CurrentMusic { get; set; }
        protected override void TryToScan()
        {
            if (ShallReturn())
                return;
            PauseIfRequested();
            lock (MusicQueue)
            {
                while (MusicQueue.Count > 0)
                {
                    if (ShallReturn())
                        return;
                    PauseIfRequested();
                    ProcessDuration(MusicQueue.Dequeue());
                }
            }
        }
        private void ProcessDuration(object state)
        {
            CurrentMusic = (Music)state;
            string status;
            string fullPath;
            Debug.WriteLine("Waiting ProcessDuration");
            lock (DatabaseManager.LockObject)
            {
                Debug.WriteLine("Lock ProcessDuration");
                status = CurrentMusic.Status;
                fullPath = CurrentMusic.FullPath;
                Debug.WriteLine("Unlock ProcessDuration");
            }
            if (status == "Playing")
            {
                IsOpening = false;
                return;
            }
            SynchronizationContextHelper.Instance.SendInBackground(d=>Playfile((string) d),fullPath);
        }

        private void Playfile(string fullPath)
        {
            MediaPlayer.Stop();
            MediaPlayer.Close();
            MediaPlayer.Open(new Uri(string.Format("file://{0}", fullPath)));
        }

        public void Add(Music music)
        {
            lock (MusicQueue)
            {
                if(MusicQueue.Contains(music)==false)
                    MusicQueue.Enqueue(music);    
            }
        }
        public void AddRange(IEnumerable<Music> musics)
        {
            foreach (var music in musics)
            {
                Add(music);
            }
        }
    }
}